package guilayer;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import modellayer.Customer;
import modellayer.PartOrder;
import modellayer.Product;
import controllayer.CustomerCTR;
import controllayer.OrderCTR;
import controllayer.ProductCTR;

public class TabSale extends JPanel
{
	private CustomerCTR cCTR;
	private ProductCTR pCTR;
	private OrderCTR oCTR;
	
	// Items for customerInfoPanel
	private JTextField txtLookupCustomer;
	private JLabel lblShowCustomerNo;
	private JLabel lblShowFirstName;
	private JLabel lblShowLastName;
	private JLabel lblShowAddress;
	private JLabel lblShowZipCode;
	private JLabel lblShowPhoneNo;
	
	// Items for productInfoPanel
	private JLabel lblShowProductName;
	private JLabel lblShowProductBarcode;
	private JLabel lblShowSalesPrice;
	private JLabel lblShowRentalPrice;
	private JLabel lblShowAvailableStock;
	private JLabel lblShowCountryOrigin;
	private JTextField txtGetBarcode;
	
	// Items for specifyAmountPanel
	private JLabel lblBigProductName;
	private JLabel lblProductDescription;
	private JLabel lblShowPricePrItem;
	private JLabel lblShowSubtotal;
	private JLabel lblShowVat;
	private JLabel lblShowPriceInclVat;
	private JComboBox comboBox;
	
	// Items for saleProductTable
	private DefaultTableModel tableModel;
	private JTable table;
	String finalSubtotal = "0.00";
	String finalVat ="0.00";
	String finalTotalInclVat = "0.00";
	
	//Items for addProduct()
	boolean orderCreated = false;
	
	//Items for Close Order Panel
	private JLabel lblFinalSubtotal;
	private JLabel lblFinalVat;
	private JLabel lblFinalPriceInclVat;

	/**
	 * Create the panel.
	 */
	public TabSale()
	{
		setLayout(null);
		
		cCTR = new CustomerCTR();
		pCTR = new ProductCTR();
		oCTR = new OrderCTR();
		
		lookUpCustomerPanel();
		customerInfoPanel();
		findProductPanel();
		productInfoPanel();
		specifyAmountPanel();
		saleProductTable();
		closeSalePanel();
	}
	
	private void lookUpCustomerPanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(10, 11, 310, 54);
		panel.setBorder(new TitledBorder(null, "LOOKUP CUSTOMER", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		JButton btnLookupCustomer = new JButton("Assign");
		btnLookupCustomer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				lookUpCostumer(getCustomerNo());
			}
		});
		btnLookupCustomer.setBounds(227, 20, 73, 23);
		panel.add(btnLookupCustomer);
		
		JLabel lblCustomerNo = new JLabel("Customer No.:");
		lblCustomerNo.setBounds(10, 24, 90, 14);
		panel.add(lblCustomerNo);
		
		txtLookupCustomer = new JTextField();
		txtLookupCustomer.setBounds(100, 21, 122, 20);
		panel.add(txtLookupCustomer);
		txtLookupCustomer.setColumns(10);
	}
	
	private void customerInfoPanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(10, 76, 310, 208);
		panel.setBorder(new TitledBorder(null, "CUSTOMER INFO", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		JLabel lblCustomerNo = new JLabel("Customer No.:");
		lblCustomerNo.setBounds(10, 25, 90, 14);
		panel.add(lblCustomerNo);
		
		JLabel lblFirstName = new JLabel("First Name:");
		lblFirstName.setBounds(10, 50, 90, 14);
		panel.add(lblFirstName);
		
		JLabel lblLastName = new JLabel("Last Name:");
		lblLastName.setBounds(10, 75, 90, 14);
		panel.add(lblLastName);
		
		JLabel lblAddress = new JLabel("Address:");
		lblAddress.setBounds(10, 100, 90, 14);
		panel.add(lblAddress);
		
		JLabel lblZipCode = new JLabel("Zip Code:");
		lblZipCode.setBounds(10, 125, 90, 14);
		panel.add(lblZipCode);
		
		JLabel lblPhoneNo = new JLabel("Phone No.:");
		lblPhoneNo.setBounds(10, 150, 90, 14);
		panel.add(lblPhoneNo);
		
		JButton btnUnassignCustomer = new JButton("Unassign Customer");
		btnUnassignCustomer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				unassignCustomer();
			}
		});
		btnUnassignCustomer.setBounds(153, 175, 147, 23);
		panel.add(btnUnassignCustomer);
		
		lblShowCustomerNo = new JLabel(">No Customer Assigned<");
		lblShowCustomerNo.setBounds(110, 25, 190, 14);
		panel.add(lblShowCustomerNo);
		
		lblShowFirstName = new JLabel("-");
		lblShowFirstName.setBounds(110, 50, 190, 14);
		panel.add(lblShowFirstName);
		
		lblShowLastName = new JLabel("-");
		lblShowLastName.setBounds(110, 75, 190, 14);
		panel.add(lblShowLastName);
		
		lblShowAddress = new JLabel("-");
		lblShowAddress.setBounds(110, 100, 190, 14);
		panel.add(lblShowAddress);
		
		lblShowZipCode = new JLabel("-");
		lblShowZipCode.setBounds(110, 125, 190, 14);
		panel.add(lblShowZipCode);
		
		lblShowPhoneNo = new JLabel("-");
		lblShowPhoneNo.setBounds(110, 150, 190, 14);
		panel.add(lblShowPhoneNo);
	}
	
	private void findProductPanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(330, 11, 310, 54);
		panel.setBorder(new TitledBorder(null, "FIND PRODUCT", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		JButton btnFind = new JButton("Find");
		btnFind.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				findProduct(txtGetBarcode.getText());
			}
		});
		btnFind.setBounds(227, 20, 73, 23);
		panel.add(btnFind);
		
		txtGetBarcode = new JTextField();
		txtGetBarcode.setBounds(100, 21, 122, 20);
		panel.add(txtGetBarcode);
		txtGetBarcode.setColumns(10);
		
		JLabel lblBarcode = new JLabel("Barcode:");
		lblBarcode.setBounds(10, 24, 90, 14);
		panel.add(lblBarcode);
	}
	
	private void productInfoPanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(330, 76, 310, 208);
		panel.setBorder(new TitledBorder(null, "PRODUCT INFO", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(10, 25, 90, 14);
		panel.add(lblName);
		
		JLabel lblBarcode_1 = new JLabel("Barcode:");
		lblBarcode_1.setBounds(10, 50, 90, 14);
		panel.add(lblBarcode_1);
		
		JLabel lblSalesPrice = new JLabel("Sales Price:");
		lblSalesPrice.setBounds(10, 75, 90, 14);
		panel.add(lblSalesPrice);
		
		JLabel lblRentalPrice = new JLabel("Rental Price:");
		lblRentalPrice.setBounds(10, 100, 90, 14);
		panel.add(lblRentalPrice);
		
		JLabel lblAvailableStock = new JLabel("Available Stock:");
		lblAvailableStock.setBounds(10, 125, 90, 14);
		panel.add(lblAvailableStock);
		
		JLabel lblCountryOrigin = new JLabel("Country Origin:");
		lblCountryOrigin.setBounds(10, 150, 90, 14);
		panel.add(lblCountryOrigin);
		
		lblShowProductName = new JLabel(">No Product Found<");
		lblShowProductName.setBounds(120, 25, 180, 14);
		panel.add(lblShowProductName);
		
		lblShowProductBarcode = new JLabel("-");
		lblShowProductBarcode.setBounds(120, 50, 180, 14);
		panel.add(lblShowProductBarcode);
		
		lblShowSalesPrice = new JLabel("-");
		lblShowSalesPrice.setBounds(120, 75, 180, 14);
		panel.add(lblShowSalesPrice);
		
		lblShowRentalPrice = new JLabel("-");
		lblShowRentalPrice.setBounds(120, 100, 180, 14);
		panel.add(lblShowRentalPrice);
		
		lblShowAvailableStock = new JLabel("-");
		lblShowAvailableStock.setBounds(120, 125, 180, 14);
		panel.add(lblShowAvailableStock);
		
		lblShowCountryOrigin = new JLabel("-");
		lblShowCountryOrigin.setBounds(120, 150, 180, 14);
		panel.add(lblShowCountryOrigin);
		
		JButton btnClearProduct = new JButton("Clear Product");
		btnClearProduct.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearProduct();
			}
		});
		btnClearProduct.setBounds(187, 175, 113, 23);
		panel.add(btnClearProduct);
	}
	
	private void specifyAmountPanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(650, 11, 310, 273);
		panel.setBorder(new TitledBorder(null, "SPECIFY AMOUNT", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		lblBigProductName = new JLabel(">No Product Found<");
		lblBigProductName.setFont(new Font("Lucida Grande", Font.BOLD, 20));
		lblBigProductName.setBounds(10, 24, 290, 26);
		panel.add(lblBigProductName);
		
		lblProductDescription = new JLabel("-");
		lblProductDescription.setBounds(10, 58, 290, 14);
		panel.add(lblProductDescription);
		
		JLabel lblPickAmount = new JLabel("Pick Amount:");
		lblPickAmount.setBounds(10, 95, 90, 14);
		panel.add(lblPickAmount);
		
		JLabel lblPricePrItem = new JLabel("Price pr. Item:");
		lblPricePrItem.setBounds(10, 130, 90, 14);
		panel.add(lblPricePrItem);
		
		JLabel lblSubtotal = new JLabel("Subtotal:");
		lblSubtotal.setBounds(10, 155, 90, 14);
		panel.add(lblSubtotal);
		
		JLabel lblVat = new JLabel("VAT:");
		lblVat.setBounds(10, 180, 90, 14);
		panel.add(lblVat);
		
		JLabel lblPriceInclVat = new JLabel("Price incl. VAT:");
		lblPriceInclVat.setBounds(10, 212, 120, 14);
		lblPriceInclVat.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		panel.add(lblPriceInclVat);
		
		lblShowPricePrItem = new JLabel("0.00");
		lblShowPricePrItem.setBounds(160, 130, 140, 14);
		lblShowPricePrItem.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblShowPricePrItem);
		
		lblShowSubtotal = new JLabel("0.00");
		lblShowSubtotal.setBounds(160, 155, 140, 14);
		lblShowSubtotal.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblShowSubtotal);
		
		lblShowVat = new JLabel("0.00");
		lblShowVat.setBounds(160, 180, 140, 14);
		lblShowVat.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblShowVat);
		
		lblShowPriceInclVat = new JLabel("0.00");
		lblShowPriceInclVat.setBounds(160, 212, 140, 14);
		lblShowPriceInclVat.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		lblShowPriceInclVat.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblShowPriceInclVat);
		
		String[] nums = {"1","2","3","4","5","6","7","8","9"};
		comboBox = new JComboBox(nums);
		comboBox.setBounds(110, 92, 60, 20);
		comboBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				calcSpecifyAmountPrice(comboBox.getSelectedIndex()+1);
			}
		});
		panel.add(comboBox);
		
		JButton btnAddProducts = new JButton("Add Product(s)");
		btnAddProducts.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				double amount = addProductToTable(lblShowProductBarcode.getText(), (comboBox.getSelectedIndex()+1));
				addProductAndPartOrderToOrder(lblShowProductBarcode.getText(), (comboBox.getSelectedIndex()+1), amount, "date", "deliveryDate", "deliveryStatus");
				setCloseSaleAmounts();
			}
		});
		btnAddProducts.setBounds(170, 239, 130, 23);
		panel.add(btnAddProducts);
	}
	
	private void saleProductTable()
	{
		String[] columnNames = {"Product Name", "Description", "Barcode", "Amount", "Price incl. VAT", "Total incl. VAT"};
		tableModel = new DefaultTableModel(null, columnNames);
		
		JScrollPane scrollPane = new JScrollPane();
		add(scrollPane);
				table = new JTable(tableModel) {  
					public boolean isCellEditable(int row,int column){  
						return false;
					}
				};
				
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setBorder(new LineBorder(new Color(0, 0, 0)));
		scrollPane.setBounds(10, 295, 950, 267);
		scrollPane.setViewportView(table);
		
		JButton btnRemoveItem = new JButton("Remove Item");
		btnRemoveItem.setBounds(129, 568, 109, 23);
		add(btnRemoveItem);
		
		JButton btnCancelSale = new JButton("Cancel Sale");
		btnCancelSale.setBounds(10, 568, 109, 23);
		add(btnCancelSale);
	}
	
	private void closeSalePanel()
	{
		JPanel panel = new JPanel();
		panel.setBounds(473, 573, 487, 105);
		panel.setBorder(new TitledBorder(null, "CLOSE SALE", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel);
		panel.setLayout(null);
		
		JLabel lblEnterPaymentAmount = new JLabel("Enter Payment Amount:");
		lblEnterPaymentAmount.setBounds(288, 25, 141, 14);
		panel.add(lblEnterPaymentAmount);
		
		JTextField textField = new JTextField();
		textField.setBounds(288, 45, 190, 20);
		panel.add(textField);
		textField.setColumns(10);
		
		JButton btnCash = new JButton("Cash");
		btnCash.setBounds(288, 70, 89, 23);
		panel.add(btnCash);
		
		JButton btnCard = new JButton("Card");
		btnCard.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				closeSale();
			}
		});
		btnCard.setBounds(389, 70, 89, 23);
		panel.add(btnCard);
		
		lblFinalSubtotal = new JLabel("0.00");
		lblFinalSubtotal.setBounds(130, 25, 119, 14);
		lblFinalSubtotal.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblFinalSubtotal);
		
		lblFinalVat = new JLabel("0.00");
		lblFinalVat.setBounds(130, 48, 119, 14);
		lblFinalVat.setHorizontalAlignment(JLabel.RIGHT);
		panel.add(lblFinalVat);
		
		lblFinalPriceInclVat = new JLabel("0.00");
		lblFinalPriceInclVat.setBounds(130, 79, 119, 14);
		lblFinalPriceInclVat.setHorizontalAlignment(JLabel.RIGHT);
		lblFinalPriceInclVat.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		panel.add(lblFinalPriceInclVat);
		
		JLabel lblSubtotal = new JLabel("Subtotal:");
		lblSubtotal.setBounds(10, 25, 110, 14);
		panel.add(lblSubtotal);
		
		JLabel lblVat = new JLabel("VAT:");
		lblVat.setBounds(10, 48, 110, 14);
		panel.add(lblVat);
		
		JLabel lblTotalInclVat = new JLabel("Total incl. VAT:");
		lblTotalInclVat.setBounds(10, 79, 110, 14);
		lblTotalInclVat.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		panel.add(lblTotalInclVat);
	}
	
	private int getCustomerNo()
	{
		int cNo = 0;
		String s = txtLookupCustomer.getText();
		
		try
		{
			cNo = Integer.parseInt(s);
		}
		catch(NumberFormatException e)
		{
			System.out.println("txtLookupCustomer.getText() didn't contain an integer. Exception: "+e);
		}
		
		return cNo;
	}
	
	private boolean lookUpCostumer(int customerNo)
	{
		boolean success = false;
		Customer c = null;
		
		if (cCTR.getCustomerByCustomerNo(customerNo) != null)
		{
			c = cCTR.getCustomerByCustomerNo(customerNo);
			
			try
			{
				lblShowCustomerNo.setText(Integer.toString(c.getCustomerNo()));
			}
			catch(NumberFormatException e)
			{
				System.out.println("c.getCustomerNo() didn't contain an integer. Exception: "+e);
			}
			
			try
			{
				lblShowFirstName.setText(c.getFirstName());
				lblShowLastName.setText(c.getLastName());
				lblShowAddress.setText(c.getAddress());
				lblShowPhoneNo.setText(c.getPhonenumber());
			}
			catch(Exception e)
			{
				System.out.println("Second try failed!");
			}
			
			try
			{
				lblShowZipCode.setText(Integer.toString(c.getZipcode()));
			}
			catch(NumberFormatException e)
			{
				System.out.println("c.getZipCode() didn't contain an integer. Exception: "+e);
			}
			
			txtLookupCustomer.setText("");
			success = true;
		}
		else
		{
			System.out.println("There was no Customer in DB with the typed CustomerNo!");
		}
		
		return success;
	}
	
	private boolean findProduct(String barcode)
	{
		boolean success = false;
		Product p = null;
		
		if (pCTR.getProductByBarcode(barcode) != null)
		{
			p = pCTR.getProductByBarcode(barcode);
			
			try
			{
				lblShowProductName.setText(p.getName());
				lblBigProductName.setText(p.getName());
				lblProductDescription.setText(p.getDescription());
				lblShowProductBarcode.setText(p.getBarcode());
				lblShowCountryOrigin.setText(p.getCountryOfOrigin());
			}
			catch(Exception e)
			{
				System.out.println("First try findProduct() failed in!");
			}
			
			try
			{
				lblShowSalesPrice.setText(Double.toString(p.getSalesPrice()));
				lblShowPricePrItem.setText(Double.toString(p.getSalesPrice()));
				lblShowRentalPrice.setText(Double.toString(p.getRentPricePrDay()));
			}
			catch(NumberFormatException e)
			{
				System.out.println("get-methods didn't contain a double. Exception: "+e);
			}
			
			txtGetBarcode.setText("");
			success = true;
		}
		else
		{
			System.out.println("There was no Product in DB with the typed Barcode!");
		}
		
		calcSpecifyAmountPrice(1);
		comboBox.setSelectedIndex(0);
		
		return success;
	}
	
	private void unassignCustomer()
	{
		lblShowCustomerNo.setText(">No Customer Assigned<");
		lblShowFirstName.setText("-");
		lblShowLastName.setText("-");
		lblShowAddress.setText("-");
		lblShowPhoneNo.setText("-");
		lblShowZipCode.setText("-");
	}
	
	private void clearProduct()
	{
		lblShowProductName.setText(">No Product Found<");
		lblBigProductName.setText(">No Product Found<");
		lblShowProductBarcode.setText("-");
		lblShowCountryOrigin.setText("-");
		lblShowSalesPrice.setText("-");
		lblShowRentalPrice.setText("-");
		lblProductDescription.setText("-");
		lblShowPricePrItem.setText("0.00");
		lblShowSubtotal.setText("0.00");
		lblShowVat.setText("0.00");
		lblShowPriceInclVat.setText("0.00");
	}
	
	private void calcSpecifyAmountPrice(double amount)
	{
		String sPricePrItem = lblShowPricePrItem.getText();
		double pricePrItem = 0;
		
		try
		{
			pricePrItem = Double.parseDouble(sPricePrItem);
		}
		catch(NumberFormatException e)
		{
			System.out.println("lblShowPricePrItem didn't contain a double. Exception: "+e);
		}
		
		lblShowSubtotal.setText(Double.toString(pricePrItem*amount));
		lblShowVat.setText(Double.toString(pricePrItem*amount*0.25));
		lblShowPriceInclVat.setText(Double.toString((pricePrItem*amount)+(pricePrItem*amount*0.25)));
	}
	
	private double addProductToTable(String barcode, int amount)
	{
		Product p = null;
		String pName = "-";
		String pDescription = "-";
		String pBarcode = "-";
		String pAmount = "-";
		String pPriceInclVat = "-";
		String pTotalInclVat = "-";
		
		if (pCTR.getProductByBarcode(barcode) != null)
		{
			p = pCTR.getProductByBarcode(barcode);
			double pricePrItem = p.getSalesPrice();
			
			pName = p.getName();
			pDescription = p.getDescription();
			pBarcode = p.getBarcode();
			pAmount = Integer.toString(comboBox.getSelectedIndex()+1);
			pPriceInclVat = Double.toString(pricePrItem+(pricePrItem*0.25));
			pTotalInclVat = Double.toString((pricePrItem+(pricePrItem*0.25))*amount);
			
			String[] rowData = {pName, pDescription, pBarcode, pAmount, pPriceInclVat, pTotalInclVat};
			
			tableModel.addRow(rowData);
		}
		else
		{
			System.out.println("No product with the given barcode found - therefore no product added to table!");
		}
		
		return Double.parseDouble(pTotalInclVat);
	}
	
	private void addProductAndPartOrderToOrder(String barcode, int qty, double amount, String date, String deliveryDate, String deliveryStatus)
	{
		if (!orderCreated)
		{
			oCTR.createOrder(date, deliveryDate, deliveryStatus);
			orderCreated = true;
		}
		oCTR.addPartOrder(new PartOrder(0, amount, qty, pCTR.getProductByBarcode(barcode)));
	}
	
	private void setCloseSaleAmounts()
	{
		lblFinalSubtotal.setText(Double.toString(oCTR.getFullAmount()-(oCTR.getFullAmount()*0.20)));
		lblFinalVat.setText(Double.toString(oCTR.getFullAmount()-(oCTR.getFullAmount()*0.80)));
		lblFinalPriceInclVat.setText(Double.toString(oCTR.getFullAmount()));
	}
	
	private void clearCloseSale()
	{
		lblFinalSubtotal.setText("-");
		lblFinalVat.setText("-");
		lblFinalPriceInclVat.setText("-");
	}
	
	private void clearTable()
	{
		tableModel.setRowCount(0);
	}
	
	private void closeSale()
	{
		int customerNo = 0;
		
		try
		{
			customerNo = Integer.parseInt(lblShowCustomerNo.getText());
		}
		catch(NumberFormatException e)
		{
			System.out.println("lblShowCustomerNo didn't contain an int. Exception: "+e);
		}
		
		if (!lblShowCustomerNo.getText().equals("-"))
		{
			oCTR.addCustomer(cCTR.getCustomerByCustomerNo(customerNo));
		}
		
		try
		{
			oCTR.closeOrder();
		}
		catch (Exception e)
		{
			System.out.println("Closing of Sale failed! Exception: "+e);
		}
		
		clearProduct();
		unassignCustomer();
		clearCloseSale();
		clearTable();
		
		orderCreated = false;
	}
}
